package com.example.job10redisscene;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.Set;

@Component
@Slf4j
public class RankLinkSet {

    @Autowired
    private RedisTemplate redisTemplate;

    public void rank() {
        String key = "scoreSet";
        redisTemplate.delete(key);
        for (int i = 0; i < 100; i++) {
            String user = "user:" + new Random(System.currentTimeMillis()).nextInt(10);
            // 相当于ZINCRBY rankingList 1 user:2
            redisTemplate.opsForZSet().incrementScore(key, user, 1);
            // 倒序排序返回集合
            final Set<String> range = redisTemplate.opsForZSet().reverseRange(key, 0, 2);
            log.info("top 3 is:");
            for (String item : range) {
                System.out.printf("%s -- %f  ", item, redisTemplate.opsForZSet().score(key, item));
            }
        }
    }


}
